package com.example.hhhh;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;


/**
 * Created by chenliu on 2016/8/26.<br/>
 * 描述：添加圆角支持 on 2016/11/11
 * </br>
 */
public class FlikerProgressBar extends AppCompatTextView implements Runnable {
    public static final int STATE_UNKNOW = -1;
    public static final int STATE_OPENING = 0;
    public static final int STATE_OPENED_FAIL = 1;
    public static final int STATE_OPENED_SUCCESS = 2;

    private String OPEN_UNKNOW_TIPS = "未知状态";//开门提示文字
    private String OPEN_TIPS = "开门中...";//开门提示文字
    private String OPEN_FAIL_TIPS = "开门失败";//开门失败提示
    private String OPEN_SUCCESS_TIPS = "开门成功";//开门成功提示


    private PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP);
    private int DEFAULT_HEIGHT_DP = 35;
    private int borderWidth;
    private float maxProgress = 100f;
    private Paint textPaint;
    private Paint bgPaint;
    private Paint pgPaint;
    //    private String progressText;
    private Rect textRect;
    private RectF bgRectf;
    /**
     * 左右来回移动的滑块
     */
    private Bitmap flikerBitmap;
    /**
     * 滑块移动最左边位置，作用是控制移动
     */
    private float flickerLeft;
    /**
     * 进度条 bitmap ，包含滑块
     */
    private Bitmap pgBitmap;
    private Canvas pgCanvas;
    /**
     * 当前进度
     */
    private float progress;
    private boolean isFinish;
    private boolean isStop;
    /**
     * 下载中颜色
     */
    private int loadingColor;
    /**
     * 暂停时颜色
     */
    private int stopColor;
    /**
     * 进度文本、边框、进度条颜色
     */
    private int progressColor;
    private int textSize;
    private int radius;
    private Thread thread;
    BitmapShader bitmapShader;

    public FlikerProgressBar(Context context) {
        this(context, null, 0);
    }

    public FlikerProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlikerProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
    }

    /**
     * 初始化提示语
     *
     * @param openDoorTips
     * @param openFailTips
     * @param openSuccessTips
     */
    public void initTips(String openDoorTips, String openFailTips, String openSuccessTips) {
        if (!TextUtils.isEmpty(openDoorTips)) {
            OPEN_TIPS = openDoorTips;
        }
        if (!TextUtils.isEmpty(openFailTips)) {
            OPEN_FAIL_TIPS = openFailTips;
        }
        if (!TextUtils.isEmpty(openSuccessTips)) {
            OPEN_SUCCESS_TIPS = openSuccessTips;
        }
    }

    private void initAttrs(AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.FlikerProgressBar);
        try {
            textSize = (int) ta.getDimension(R.styleable.FlikerProgressBar_textSize, 12);
            loadingColor = ta.getColor(R.styleable.FlikerProgressBar_loadingColor, Color.parseColor("#40c4ff"));
            stopColor = ta.getColor(R.styleable.FlikerProgressBar_stopColor, Color.parseColor("#00ffffff"));
            radius = (int) ta.getDimension(R.styleable.FlikerProgressBar_radius, 0);
            borderWidth = (int) ta.getDimension(R.styleable.FlikerProgressBar_borderWidth, 1);
        } finally {
            ta.recycle();
        }
    }

    private void init() {
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setStrokeWidth(borderWidth);

        pgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pgPaint.setStyle(Paint.Style.FILL);

        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(textSize);

        textRect = new Rect();
        bgRectf = new RectF(borderWidth, borderWidth, getMeasuredWidth() - borderWidth, getMeasuredHeight() - borderWidth);

        if (isStop) {
            progressColor = stopColor;
        } else {
            progressColor = loadingColor;
        }

        flikerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        flickerLeft = -flikerBitmap.getWidth();

        initPgBimap();
    }

    private void initPgBimap() {
        pgBitmap = Bitmap.createBitmap(getMeasuredWidth() - borderWidth, getMeasuredHeight() - borderWidth, Bitmap.Config.ARGB_8888);
        pgCanvas = new Canvas(pgBitmap);
        thread = new Thread(this);
        thread.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        int height = 0;
        switch (heightSpecMode) {
            case MeasureSpec.AT_MOST:
                height = dp2px(DEFAULT_HEIGHT_DP);
                break;
            case MeasureSpec.EXACTLY:
            case MeasureSpec.UNSPECIFIED:
                height = heightSpecSize;
                break;
        }
        setMeasuredDimension(widthSpecSize, height);

        if (pgBitmap == null) {
            init();
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景
        drawBackGround(canvas);
        //进度
        drawProgress(canvas);
    }

    /**
     * 边框
     *
     * @param canvas
     */
    private void drawBackGround(Canvas canvas) {
        bgPaint.setColor(progressColor);
        //left、top、right、bottom不要贴着控件边，否则border只有一半绘制在控件内,导致圆角处线条显粗
        canvas.drawRoundRect(bgRectf, radius, radius, bgPaint);
    }

    /**
     * 进度
     */
    private void drawProgress(Canvas canvas) {
        pgPaint.setColor(progressColor);

        float right = (progress / maxProgress) * getMeasuredWidth();
        pgCanvas.save();
        pgCanvas.clipRect(0, 0, right, getMeasuredHeight());
        pgCanvas.drawColor(progressColor);
        pgCanvas.restore();

        //控制显示区域
        bitmapShader = new BitmapShader(pgBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        pgPaint.setShader(bitmapShader);
        canvas.drawRoundRect(bgRectf, radius, radius, pgPaint);
    }

    public void setProgress(float progress) {
        if (!isStop) {
            if (progress < maxProgress) {
                this.progress = progress;
            } else {
                this.progress = maxProgress;
                finishLoad();
            }
            invalidate();
        }
    }

    public void setStop(boolean stop) {
        isStop = stop;
        if (isStop) {
            progressColor = stopColor;
            thread.interrupt();
        } else {
            progressColor = loadingColor;
            thread = new Thread(this);
            thread.start();
        }
        invalidate();
    }

    public void finishLoad() {
        isFinish = true;
        setStop(true);
    }

    @Override
    public void run() {
        int width = flikerBitmap.getWidth();
        try {
            while (!isStop && !thread.isInterrupted()) {
                progress = progress + 10;
                flickerLeft += dp2px(5);
                float progressWidth = (progress / maxProgress) * getMeasuredWidth();
                if (flickerLeft >= progressWidth) {
                    flickerLeft = -width;
                }
                Message message = handler.obtainMessage();
                message.arg1 = (int) progress;
                handler.sendMessage(message);
                if (progress == 100) {
                    break;
                }
                postInvalidate();
                Thread.sleep(20);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            setProgress(msg.arg1);
            if (msg.arg1 == 100) {

            }
        }
    };

    /**
     * 重置
     */
    public void reset() {
        setStop(true);
        progress = 0;
        isFinish = false;
        isStop = false;
        progressColor = loadingColor;
        flickerLeft = -flikerBitmap.getWidth();
        initPgBimap();
    }

    public float getProgress() {
        return progress;
    }

    private int dp2px(int dp) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * density);
    }

    /**
     * 开门
     */
    public void openDoor() {
        reset();
        updateOpenState(STATE_OPENING);
        isStop = false;
    }

    /**
     * 更新开门状态
     */
    public void updateOpenState(int state) {
        switch (state) {
            case STATE_OPENING:
                setBackground(ContextCompat.getDrawable(getContext(), R.drawable.shape_circular_ff00a0e9));
                setText(OPEN_TIPS);
                break;
            case STATE_OPENED_SUCCESS:
                setBackground(ContextCompat.getDrawable(getContext(), R.drawable.shape_circular_ff00a0e9));
                setText(OPEN_SUCCESS_TIPS);
                break;
            case STATE_OPENED_FAIL:
                setBackground(ContextCompat.getDrawable(getContext(), R.drawable.shape_circular_red));
                setText(OPEN_FAIL_TIPS);
                break;
            case STATE_UNKNOW:
                setBackground(ContextCompat.getDrawable(getContext(), R.drawable.shape_circular_red));
                setText(OPEN_UNKNOW_TIPS);
                break;
        }
    }

    //释放资源
    public void release() {
        if (thread != null) {
            isStop = true;
            thread.interrupt();
            thread = null;
        }
        if (flikerBitmap != null) {
            flikerBitmap.recycle();
            flikerBitmap = null;
        }
        if (pgBitmap != null) {
            pgBitmap.recycle();
            pgBitmap = null;
        }
    }
}
